﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
using System;
using System.Threading;

namespace Cache.RedisDistributed.Locks
{
    /// <summary>
    /// Redis分布式锁
    /// </summary>
    public class RedisLock
    {
        // 1、redis连接管理类
        private ConnectionMultiplexer connectionMultiplexer = null;

        // 2、redis数据操作类
        private IDatabase database = null;
        public RedisLock()
        {
            var conn = "192.168.190.128:6379";
            connectionMultiplexer = ConnectionMultiplexer.Connect(conn);
            database = connectionMultiplexer.GetDatabase(0);
        }

        public void Lock()
        {
            while (true)
            {
                bool flag = database.LockTake("redis-lock", Thread.CurrentThread.ManagedThreadId, TimeSpan.FromSeconds(60));
                if(flag)
                {
                    //flag:true 加锁成功，false 加锁失败
                    break;
                }
                // 防止死循环。通过等待时间，释放资源
                Thread.Sleep(10);
            }
        }

        /// <summary>
        /// 解锁
        /// </summary>
        public void UnLock()
        {
            bool flag = database.LockRelease("redis-lock", Thread.CurrentThread.ManagedThreadId);

            // true:释放成功  false 释放失败
            // 方案：释放资源
            connectionMultiplexer.Close();
        }
    }
}
